/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int preIndex = 0;
    public TreeNode createTreeByPandI(int[] preorder,int[] inorder,int inbegin,int inend){
        //如果这个条件满足 说明没有左树 或者 右树 了
        if(inbegin > inend) return null;
        TreeNode root = new TreeNode(preorder[preIndex]);
        //找到根节点在中序遍历中的位置
        int rootIndex = findIndex(inorder,inbegin,inend,root.val);
        if(rootIndex == -1) return null;
        preIndex++;
        //分别创建左子树和右子树
        root.left = createTreeByPandI(preorder,inorder,inbegin,rootIndex-1);
        root.right = createTreeByPandI(preorder,inorder,rootIndex+1,inend);
        return root;
    }

    private int findIndex(int[] inorder,int inbegin,int inend,int key){
        for(int i = inbegin ; i <= inend ; i++){
            if(inorder[i] == key)
            return i;
        }
        return -1;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder == null || inorder == null) return null;
        return createTreeByPandI(preorder,inorder,0,inorder.length-1);
    }
}